using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for TransactionDocument
/// </summary>
public class TransactionDocument
{
    DataSet dsePageInfo = new DataSet();
    DataSet dseInputInfo = new DataSet();
    string child_pagesetid = "";
    HtmlForm frmObj;
    string strErrMessage = "";
    DataSet dsePageInfoMain = null;
    HDDatabase HDD = new HDDatabase();
    DataSet dsInput = new DataSet();
//    TransactionDocDisplayI TDDI;
	public TransactionDocument()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public DataSet createChildPage(string masterpageid,ref HtmlForm frmObj,string sortby,DataSet dsTax)
    {
        DataSet dsechildInfo = new DataSet();
        bool status = false;
        Master MA = new Master();
        child_pagesetid = getchildpagesetid(masterpageid);
        if(child_pagesetid!="")
        {
            
            
            
            if (frmObj != null)
            {
                //loadAllVariables();
                //GlobalValues.hsSysVar = sysVar;
                //frmObj = (HtmlForm)this.Master.FindControl("Form1");
                PageInfoLoad PIL = new PageInfoLoad();
                dsePageInfo = PIL.GetPageSetPageCtrlInfo(child_pagesetid);
                //if (HttpContext.Current.Request.QueryString["DPK"] != null)  //Commented by srivatsan for delete issue
                //{
                //    string strDelKey = HttpContext.Current.Request.QueryString["DPK"].ToString().Replace("'", "''");
                //    bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                //}

                if (HttpContext.Current.Session["DPK"] != null)
                {
                    string strDelKey = HttpContext.Current.Session["DPK"].ToString().Replace("'", "''");
                    bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                }

                if (HttpContext.Current.Request.QueryString["PK"] != null)  //Added by srivatsan
                {
                    string PKaf_row_id = HttpContext.Current.Request.QueryString["PK"].ToString();
                    string sql = "select attrib_id from sy_obj_mas_detail where object_id in(select af_row_id from sy_obj where object_id = '"+dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString()+"')";
                    string attrib_id = HDD.GetColumnValue(sql);
                    if (!frmObj.Page.IsPostBack)  // added on May 26 for delete operation
                    {
                        string query = "select * from " + dsePageInfo.Tables["Page"].Rows[0]["page_table_name"].ToString() + " where " + attrib_id + "='" + PKaf_row_id + "'";
                        if (sortby.Trim() != "")
                        {
                            query = query + " order by "+ sortby;
                        }

                            

                        dsInput = HDD.GetDataset(query);
                        //added by Sampath on 10-Nov-2011 for Encoding
                        //CommonFunctions.decodeData(dsInput);
                    }
                }
                
                //TransactionDocDisplayI TDDI = new TransactionDocDisplayI();
                DynamicDisplayI DDI = new DynamicDisplayI();

               //dsechildInfo = TDDI.Load(child_pagesetid, frmObj, dsePageInfo,dsInput);
                DDI.Load(child_pagesetid,frmObj, ref dsePageInfo, dsInput,dsTax);
               dsechildInfo = dsePageInfo;

               if (!frmObj.Page.IsPostBack)
               {
                   CheckEditOperation(frmObj);

                   //UpdateHiddenFieldValues(frmObj, dsInput, dsechildInfo.Tables["PageCtrl"].Select(), dsechildInfo.Tables["Page"].Rows[0]["page_id"].ToString());
               }
            }



            status = true;

        }

        //if (!frmObj.Page.IsPostBack)
       // {
         //   PageControlEvents PCE = new PageControlEvents();
         //   PCE.DoControlEvents(frmObj, dsePageInfo);
       // }

        ////if (!frmObj.Page.IsPostBack)
        ////{
          // updateTotals(frmObj);
        ////}
        
        

        //return status;
        return dsechildInfo;

    }

    public string getChildSortBy(string masterpageid)
    {
        string result = "";
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select sort_by from sy_transaction_document where master_object = '" + masterpageid + "'";
            result = HDD.GetColumnValue(sql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: getChildSortBy :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }
    public string getchildpagesetid(string masterpageid)
    {
        HDDatabase HDD = new HDDatabase();
        string sql = "";
        string childpageid = "";
        string childpageset_id = "";
        try
        {
            sql = "select child_object from sy_transaction_document where master_object = '" + masterpageid + "'";
            childpageid = HDD.GetColumnValue(sql);

            sql = "select C.pageset_id from sy_pg A, sy_pgs_mem B , sy_pgs C where A.page_id = B.page_id and B.pageset_id = C.af_row_id and A.af_row_id = '" + childpageid + "'";
            childpageset_id = HDD.GetColumnValue(sql);

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error getchildpagesetid :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return childpageset_id;

    }

    private bool CheckEditOperation(HtmlForm frmObj)
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        //if (Page.IsPostBack == false)
        //{
        if (HttpContext.Current.Request.QueryString["PK"] != null)
        {
            strPageKey = HttpContext.Current.Request.QueryString["PK"].ToString();
            IsEdit = true;
        }
        if (IsEdit)
        {
            Master MA = new Master();
            blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
            if (blnStatus == false)
            {
                strErrMessage = MA.ErrorMessage;
                HttpContext.Current.Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
            }
        }
        //}


        return blnStatus;
    }

    private bool Load(string strPgsId, HtmlForm frmObj, DataSet dsePageInfo,DataSet dsTax)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        bool blnStatus = true;
        HtmlTable htaMain = new HtmlTable();
        htaMain.ID = "tblDynamicMain1";
        htaMain.Width = "100%";
        string strPageId = "";

        dsePageInfoMain = dsePageInfo;

        DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
        DataTable dtaPage = dsePageInfo.Tables["Page"];
        DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
        DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];
        dtaPageCtrl.Columns.Add(new DataColumn("attrib_size"));

        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            string sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();
            DataTable dtAttrib_Size = HDD.GetDataTable("select attrib_id, attrib_size, attrib_data_type from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + dtaPage.Rows[i]["object_id"].ToString() + "'");

            foreach (DataRow dr in dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'"))
            {
                DataRow[] drr = dtAttrib_Size.Select("attrib_id = '" + dr["control_attrib_id"].ToString() + "'");
                if (drr.Length > 0)
                {
                    if (drr[0]["attrib_data_type"].ToString() == "TX")
                        dr["attrib_size"] = drr[0]["attrib_size"].ToString();
                }
            }

            DDI.LoadPageMember(dtaPage, frmObj, htaMain, dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'", "control_seq asc"), dtaPageKeys, i,dsInput,dsTax);
        }

        HtmlTableCell htcObj = (HtmlTableCell)FindControl(frmObj.Controls, "tdcPagedetail");//HtmlTableCell htcObj = (HtmlTableCell)frmObj.FindControl("tdcPage");        
        htaMain.Border = 0;
        htaMain.CellPadding = 0;
        htaMain.CellSpacing = 0;
        htaMain.EnableViewState = false;
        htcObj.Controls.Add(htaMain);

        return blnStatus;
    }

    public Control FindControl(ControlCollection frmControl, string strControlId)
    {
        Control cRet = null;
        foreach (Control con in frmControl)
        {
            if (con.ID != null)
                if (con.ID.ToLower() == strControlId.ToLower())
                    return con;
        }

        foreach (Control cn in frmControl)
            if (cn.Controls.Count > 0)
            {
                cRet = FindControl(cn.Controls, strControlId);
                if (cRet != null) break;
            }
        return cRet;
    }

    private DataSet getChildData(string PKaf_row_id)
    {
        DataSet ds = new DataSet();
        string tablename = "";
        try
        {
            if (dsePageInfo != null)
            {
                if (dseInputInfo.Tables["Page"] != null)
                {
                    tablename = dseInputInfo.Tables["Page"].Rows[0]["page_table_name"].ToString();
                    if (tablename != "")
                    {
                        HDD.GetDataset("select * from "+tablename+" where ");
                    }
                }

            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error getChildData : "+ex.Message);
        }
        return ds;

    }

    public void updateTotals(HtmlForm htmlform)
    {
        //TransactionDocDisplayI TDDI = new TransactionDocDisplayI();
       
        DataRow[] drTotals = getTotalFields(dsePageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString());

        int rowcount = 1;
        if (dsInput != null)
        {
            if (dsInput.Tables.Count > 0)
            {
                rowcount = dsInput.Tables[0].Rows.Count;
            }
            else
            {
                rowcount = Convert.ToInt32(HttpContext.Current.Session["hfrowcount"].ToString());
            }

        }
        else
        {
            rowcount = Convert.ToInt32(HttpContext.Current.Session["hfrowcount"].ToString());
        }

        
        updateTotalFields(htmlform, drTotals, dsePageInfo, rowcount);
    }

    public void updateTotalFields(HtmlForm form, DataRow[] drTotals, DataSet dseChildPageInfo, int rowcount)
    {
        //TDDI = new TransactionDocDisplayI();
        try
        {
            if (form != null)
            {
                if (drTotals.Length > 0)
                {
                    for (int i = 0; i < drTotals.Length; i++)
                    {
                        string attrib_id = drTotals[i]["attrib_id"].ToString();


                        string totalfieldid = "total_" + dseChildPageInfo.Tables["Page"].Rows[0]["page_id"].ToString() + "_" + drTotals[i]["attrib_id"].ToString();

                        Control cn = FindControl(form.Controls, totalfieldid);
                        Label lbl = (Label)cn;
                        lbl.CssClass = "controlLabelFont";

                        Double total = 0;

                        for (int j = 1; j <= rowcount; j++)
                        {
                            string control_id = dseChildPageInfo.Tables["Page"].Rows[0]["page_id"].ToString() + "_" + drTotals[i]["attrib_id"].ToString()+"_"+j;
                            Control con = FindControl(form.Controls, control_id);

                            if (con is TextBox)
                            {
                                TextBox text = (TextBox)con;
                                total = total + Convert2Double(text.Text);
                            }
                            if (con is DropDownList)
                            {
                                DropDownList drop = (DropDownList)con;
                                total = total + Convert2Double(drop.SelectedValue);
                            }

                        }

                            //foreach (DataRow dr in dsChildInputInfo.Tables[0].Rows)
                           // {
                            //    total = total + TDDI.Convert2Double(dr[attrib_id].ToString());
                            //}


                        lbl.Text = total.ToString("#,##0.00");

                    }
                }
            }
        }
        catch (Exception ex)
        {

        }
    }

    private Double Convert2Double(string txt)
    {
        Double result = 0;
        try
        {
            if (txt == "")
            {

            }
            else
            {
                result = double.Parse(txt);
            }
        }
        catch (Exception ex)
        {
            result = 0;
        }
        return result;

    }

    private void UpdateHiddenFieldValues(HtmlForm frmObj,DataSet dsInput,DataRow[] drrpgctr,string page_id)
    {
        try
        {
            if (HttpContext.Current.Request.QueryString["PK"] != null)
            {
                if (dsInput != null)
                    if (dsInput.Tables.Count > 0)
                        if (dsInput.Tables[0].Rows.Count > 0)
                        {
                            int rowcount = dsInput.Tables[0].Rows.Count;
                            if (drrpgctr.Length > 0)
                            {
                                for (int j = 0; j < rowcount; j++)
                                {
                                    for (int i = 0; i < drrpgctr.Length; i++)
                                    {
                                        if (!(drrpgctr[i]["control_visible"].ToString() != "" ? Convert.ToBoolean(drrpgctr[i]["control_visible"].ToString()) : false))
                                        {
                                            int rowcnt = j + 1;
                                            string controlid = page_id + "_" + drrpgctr[i]["control_id"].ToString() + "_" + rowcnt;
                                            if (frmObj.FindControl(controlid) != null)
                                            {
                                                Control con = frmObj.FindControl(controlid);
                                                HiddenField hf = (HiddenField)con;
                                                hf.EnableViewState = false;
                                                hf.Value = dsInput.Tables[0].Rows[j][drrpgctr[i]["control_attrib_id"].ToString()].ToString();
                                            }

                                        }
                                    }
                                }
                            }
                        }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateHiddenFieldValues :"+ ex.Message);
        }
    }

    private string getPagesetId(string Object_Id)
    {
        string strPagesetRowId = "";
        try
        {
            string sPage_id = "";
            string sAF_ROW_ID = "";
            string sSql = "";
            sSql = "select object_id from sy_obj where af_row_id='" + Object_Id + "'";
            Object_Id = HDD.GetColumnValue(sSql);
            sSql = "select page_id from sy_pg where object_id='" + Object_Id + "'";
            sPage_id = HDD.GetColumnValue(sSql);
            sSql = "select pageset_id from sy_pgs_mem where page_id='" + sPage_id + "'";
            strPagesetRowId = HDD.GetColumnValue(sSql);
            //sSql = "select pageset_id from sy_pgs where af_row_id='" + sAF_ROW_ID + "'";
            //strPagesetRowId = HDD.GetColumnValue(sSql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getPagesetId : Error : " + ex.Message);
        }
        return strPagesetRowId;
    }
    private DataRow[] getTotalFields(string pageid)
    {
        DataSet ds = new DataSet();
        DataRow[] dr = null;
        try
        {
            string sql = "select * from sy_trans_doc_totals where page_id = '" + pageid + "'";
            ds = HDD.GetDataset(sql);

            dr = ds.Tables[0].Select();

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error getTotalFields :" + ex.Message);
        }
        return dr;
    }

}
